<?php
class NewretailwxauthController extends Controller
{
    public function actionWxLogin()
    {
        app()->wxUser->logout();
        $callback_landing = app()->request->getParam('callback_landing', '');
        $post_data = app()->request->getParam('post_data', '');
//http://comch.visastandards.com/wxauth/authcallback?code=0118aOmb0hKFCu1Og3nb0rRXmb08aOmw&state=OauthState%3A1536217684.7131_91925
        return app()->NewretailWxInterface->oAuthLogin(
            aUrl('/newretailwxauth/authcallback'),
            array(
                'callback_landing' => $callback_landing,
                'post_data' => $post_data,
            ),
            'code', 'snsapi_base'
        );
    }

    public function actionWxLogout()
    {
        app()->wxUser->logout();
    }

    public function actionAuthcallback()
    {
        $code = app()->request->getParam('code', '');
        $state = app()->request->getParam('state', array());

        if($stateValue = app()->NewretailWxInterface->getOauth2State($state)){
            $retAccessToken = app()->NewretailWxInterface->getOauth2AccessToken($code);

            if(!isset($retAccessToken->errcode)){
                $dbUser = NewretailUser::model()->findByAttributes(array(
                    'wx_openid' => $retAccessToken->openid,
                ));

                if(empty($dbUser)){
                    $dbUser = new NewretailUser();
                    $dbUser->wx_openid = $retAccessToken->openid;
                    $dbUser->create_time = date('Y-m-d H:i:s');
                    $dbUser->save(false);
                }

                app()->wxUser->authLogin($dbUser);

                return $this->render('authcallback', array(
                    'callback_url' => $stateValue->callback_landing,
                    'post_data' => json_decode($stateValue->post_data, true),
                ));
            }
        }

        return $this->render('error', array(
            'message' => '不好意思，出了点小问题 :(',
        ));
    }

    public function accessRules()
    {
        return array(
            array(
                'allow',
                'actions' => array('wxlogin', 'wxlogout', 'authcallback'),
                'expression' => 'app()->user->anyone'
            ),

            array(
                'deny',	//should be 'deny', 'allow' is used to give convenient to make test
                'users' => array('*'),
                'redirect' => '/user/login'
            )
        );
    }
}